package com.fit.pages.user;

import java.util.List;

import org.apache.tapestry5.SelectModel;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.util.EnumSelectModel;


import com.fit.dao.user.UserDAO;
import com.fit.entities.User;
import com.fit.model.userType.UserType;
import com.fit.pages.Confirmation;


public class AddUser {

	

	@Property
	private List <User> users;
	
	@Property
	private User user;
	
	@Persist
	private String msg;
	
	@Property
	@Persist
	private String ErrorMsg;
	
	@Inject
	private UserDAO UserDAO;
	
	@Inject
	private Messages messages;
	
	@InjectPage
	private Confirmation confirmation;
	
	@Property
	@Persist
	private UserType userType;
	
	@InjectPage
	private AddUser addUser;
	
	void onActivate(){
		users = UserDAO.findAll();
	}
	
	
	public SelectModel getUserTypes() {
		return new EnumSelectModel(UserType.class, messages);
	}
	

	Object onSuccess() {
		confirmation.setError("");
		confirmation.setConfirmation("");
		User temp = UserDAO.findByID(user.getId());
		
		if (temp == null) {
			for (int i = 0; i < users.size(); i++) {
				if(user.getUsername().equalsIgnoreCase(users.get(i).getUsername())){
					msg="";
					ErrorMsg = "That username already exists";
					return null;
				}
					
			}
			user.setType(userType.toString());
			if (UserDAO.save(user)) {
				//confirmation.setConfirmation(u"Language successfully inserted!");
				ErrorMsg="";
				msg="User successfully added!";
				return addUser;
			}
			confirmation.setConfirmation("Language is null!");
			return confirmation;
		}

		confirmation.setError("Language with " + user.getId()
				+ " ID already exists!");

		return confirmation;
	}
	

	@OnEvent(component = "deleteLink")
	Object onDeleteLink(Long id) {
		try {
			UserDAO.deleteByID(id);
			ErrorMsg="";
			msg="User successfully deleted!";
			return null;
		} catch (Exception e) {
			confirmation.setConfirmation("Greska prilikom brisanja zapisa korisnika! ");			
			return confirmation;
		}
	}


	public String getMsg() {
		return msg;
	}


	public void setMsg(String msg) {
		this.msg = msg;
	}


	
	
	
}
